<?php

namespace common\models\c2\entity;

use backend\models\c2\entity\rbac\BeUser;
use cza\base\models\statics\EntityModelStatus;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\helpers\ArrayHelper;
use yii\validators\RequiredValidator;

/**
 * This is the model class for table "{{%lottery}}".
 *
 * @property string $id
 * @property integer $type
 * @property string $name
 * @property string $label
 * @property string $activity_id
 * @property integer $need_score
 * @property string $created_by
 * @property string $updated_by
 * @property string $content
 * @property integer $status
 * @property string $created_at
 * @property string $updated_at
 */
class LotteryModel extends \cza\base\models\ActiveRecord
{
    public $items;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%lottery}}';
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            BlameableBehavior::className()
        ]); // TODO: Change the autogenerated stub
    }

    public function extraFields()
    {
        return [
            'prizes' => function ($item) {
                return $item->getPrizesArr();
            }
        ]; // TODO: Change the autogenerated stub
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['activity_id', 'created_by', 'updated_by'], 'integer'],
            [['content'], 'string'],
            [['created_at', 'updated_at'], 'safe'],
            [['type', 'status'], 'integer', 'max' => 4],
            [['name', 'label'], 'string', 'max' => 255],
            [['need_score'], 'string', 'max' => 100],
            [['items'], 'validateItems'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app.c2', 'ID'),
            'type' => Yii::t('app.c2', 'Type'),
            'name' => Yii::t('app.c2', 'Name'),
            'label' => Yii::t('app.c2', 'Label'),
            'activity_id' => Yii::t('app.c2', 'Activity ID'),
            'need_score' => Yii::t('app.c2', 'Need Score'),
            'created_by' => Yii::t('app.c2', 'Created By'),
            'updated_by' => Yii::t('app.c2', 'Updated By'),
            'content' => Yii::t('app.c2', 'Content'),
            'status' => Yii::t('app.c2', 'Status'),
            'created_at' => Yii::t('app.c2', 'Created At'),
            'updated_at' => Yii::t('app.c2', 'Updated At'),
        ];
    }

    public function validateItems($attribute)
    {
        $items = $this->$attribute;

        foreach ($items as $index => $row) {
            $requiredValidator = new RequiredValidator();
            $error = null;
            $requiredValidator->validate($row['prize_id'], $error);
            if (!empty($error)) {
                $key = $attribute . '[' . $index . '][prize_id]';
                $this->addError($key, $error);
            }
        }
    }

    /**
     * @inheritdoc
     * @return \common\models\c2\query\LotteryQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \common\models\c2\query\LotteryQuery(get_called_class());
    }

    /**
     * setup default values
     **/
    public function loadDefaultValues($skipIfSet = true)
    {
        parent::loadDefaultValues($skipIfSet);
    }

    public function getCreator()
    {
        return $this->hasOne(BeUser::className(), ['id' => 'created_by']);
    }

    public function getActivity()
    {
        return $this->hasOne(ActivityModel::className(), ['id' => 'activity_id']);
    }

    public function getPrizes()
    {
        return $this->hasMany(LotteryPrizeModel::className(), ['id' => 'prize_id'])
            ->where(['status' => EntityModelStatus::STATUS_ACTIVE])
            ->viaTable('{{%lottery_prize_rs}}', ['lottery_id' => 'id']);
    }

    public function getLotteryPrizeRs()
    {
        return $this->hasMany(LotteryPrizeRsModel::className(), ['lottery_id' => 'id']);
    }

    public function loadItems()
    {
        $this->items = $this->lotteryPrizeRs;
    }

    public function afterSave($insert, $changedAttributes)
    {
        if (!empty($this->items)) {
            foreach ($this->items as $item) {
                $attributes = [
                    'prize_id' => isset($item['prize_id']) ? $item['prize_id'] : 0,
                    'chance' => isset($item['chance']) ? $item['chance'] : 0.00,
                    'position' => isset($item['position']) ? $item['name'] : 0,
                ];
                if (isset($item['id']) && $item['id'] == '') {
                    $itemModel = new LotteryPrizeRsModel();
                    $itemModel->setAttributes($attributes);
                    $itemModel->link('lottery', $this);
                } elseif (isset($item['id'])) {
                    $itemModel = LotteryPrizeRsModel::findOne($item['id']);
                    $itemModel->updateAttributes($attributes);
                }
            }
        }
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
    }

    public function getPrizesArr()
    {
        $result = [];
        foreach ($this->prizes as $prize) {
            $arr = [];
            $arr['text'] = $prize->name;
            $arr['img'] = $prize->getThumbnailUrl();
            array_push($result, $arr);
        }
        return $result;
    }

}
